﻿using System;
using System.Data.Linq;
using System.Reflection;
using Portal.Core.Binding;
using Portal.Data.Entity;

namespace Portal.Data.Helper
{
    /// <summary>
    /// Action with Database with check in permission.
    /// </summary>
    public class ORMHelper
    {
        #region Ctor
        private ORMHelper()
        {
        }
        #endregion

        #region implement singleton pattern
        private static class Singleton
        {
            /// <summary>
            /// Using for skip checking permission
            /// </summary>
            public static readonly ORMHelper InstanceIgnorePermission = new ORMHelper();

            /// <summary>
            /// Using for checking permission
            /// </summary>
            public static readonly ORMHelper Instance = new ORMHelper();
        }

        /// <summary>
        /// Instance with checking permission
        /// </summary>
        public static ORMHelper Instance
        {
            get
            {
                return Singleton.Instance;
            }
        }
        /// <summary>
        /// Instance with none checking permission, none Clear Cache
        /// </summary>
        public static ORMHelper InstanceIgnorePermission
        {
            get
            {
                return Singleton.InstanceIgnorePermission;
            }
        }
        #endregion

        public void Save(object obj)
        {
            var bo = (BaseObject)obj;
            //check JOINKEY
            ReflectionHelper.SetJoinKeyValue(ref obj);

            using (var context = new CmsDataContext())
            {
                context.GetTable(bo.GetType()).InsertOnSubmit(bo);
                context.SubmitChanges();
            }
        }

        public void Update(object obj)
        {
            var bo = (BaseObject)obj;
            using (var context = new CmsDataContext())
            {
                context.GetTable(bo.GetType()).Attach(bo);
                context.Refresh(RefreshMode.KeepCurrentValues, bo);
                context.SubmitChanges();
            }
        }

        public void Delete(object obj)
        {
            var bo = (BaseObject)obj;
            using (var context = new CmsDataContext())
            {
                context.GetTable(bo.GetType()).Attach(bo);
                context.GetTable(bo.GetType()).DeleteOnSubmit(bo);
                context.SubmitChanges();
            }
        }

        public void Delete(Type type, object id)
        {
            MethodInfo m = type.GetMethod("FindByPrimaryKey");
            object obj = m.Invoke(null, new[] { id }) as CmsDataContext;
            if (obj != null)
            {
                Delete(obj);
            }
        }
    }
}
